package com.shop.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.entity.Res;
import com.shop.entity.UserOrder;
import com.shop.service.UserOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-03-08
 */
@RestController
@RequestMapping("/user-order")
public class UserOrderController {
    @Autowired
    UserOrderService userOrderService;

    @GetMapping("list")
    public Res list (String userName) {
        List<UserOrder> list = userOrderService.list(new QueryWrapper<UserOrder>().eq("user_name", userName));
        List<UserOrder> list1 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            UserOrder userOrder = list.get(list.size() - 1 - i);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(userOrder.getCreateTime());
            Date date = null;
            try {
                date = simpleDateFormat.parse(format);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            userOrder.setCreateTime(date);
            list1.add(userOrder);
        }
        list = list1;
        return Res.success(list);
    }
    @GetMapping("pageList")
    public Res listPage(Integer start,Integer offset){
        List<UserOrder> list = userOrderService.list();
        List<UserOrder> list1 = new ArrayList<>(list.size());
        for (int i = 0; i < list.size(); i++) {
            list1.add(list.get(list.size() - 1 - i));
        }
        list = list1;
        List<UserOrder> orderList = list.subList(start >= list.size() ? list.size() : start, Math.min(start + offset, list.size()));
        return Res.success(orderList);
    }
    @GetMapping("count")
    public Res count () {
        return Res.success(userOrderService.count());
    }

    @PostMapping("send")
    public Res send(@RequestBody HashMap<String,String> params) {
        String id = params.get("id");
        UserOrder userOrder = new UserOrder();
        userOrder.setLogistics(UserOrderService.SEND);
        userOrder.setId(id);
        boolean update = userOrderService.updateById(userOrder);
        return update?Res.success():Res.error();
    }

    @PostMapping("recive")
    public Res recive(@RequestBody HashMap<String,String> params) {
        String id = params.get("id");
        UserOrder userOrder = new UserOrder();
        userOrder.setLogistics(UserOrderService.SIGNED);
        userOrder.setId(id);
        boolean update = userOrderService.updateById(userOrder);
        return update?Res.success():Res.error();
    }
}

